/*
 * This file is part of Iqm.
 * Copyright (c) 2010-2011 Helmut Ahammer
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewTemplateGUI.java
 * Created on 25.11.2010, 08:17:13
 */
package opgui.preferences;

import java.util.ArrayList;
import java.util.List;
import javax.media.jai.ParameterBlockJAI;
import main.IqmTools;
import opgui.IqmOperatorJFrame;
import opgui.preferences.jaixml.JaiOperationDescriptor;
import opgui.preferences.jaixml.JaiPreferences.ParameterBlock;

/**
 * This is a GUI for managing templates
 * @author Philipp W. <java@scaenicus.net>
 */
public class TemplateManagerGUI extends javax.swing.JFrame {

    private List<JaiOperationDescriptor> jaiTemplates;
    private boolean userHasToChangeName = false;
    private boolean userWantsToChangeName = false;
    private final IqmOperatorJFrame callingGUI;
    private javax.swing.DefaultComboBoxModel templateList = null;
    private String lastTemplatename = null;

    /** Creates new form NewTemplateGUI */
    public TemplateManagerGUI(IqmOperatorJFrame callingGUI) {
        this.callingGUI = callingGUI;
        initComponents();
        getChooseParameterBlock();
    }

    /**
     * This function permanently deletes a template from the jaitemplates.xml.
     * @author Philipp W. <java@scaenicus.net>
     * @param templatename Name of the template to be deleted.
     */
    private void deleteTemplate(String templatename) {
        IqmTools.getJaiTemplatesXML().deleteTemplateByName(IqmTools.getCurrImgProcessFunc(), templatename);
    }

    /**
     * This function is called to fill the combo-box with appropriate templates from jaitemplates.xml.<br />
     * The entries are sorted alphabetically, but the first entry is "default" and the last is "New Template".<br />
     * If no template is found in jaitemplates.xml this function also generates a new "default" template from the hard-coded default values and saves them to jaitemplates.xml.
     * @author Philipp W. <java@scaenicus.net>
     */
    private void fillChooseParameterBlock() {
        templateList.removeAllElements();
        String currFunc = IqmTools.getCurrImgProcessFunc();
        List<String> callstrings = new ArrayList<String>();
        boolean defaultisset = false;

        ParameterBlock xmlPB = IqmTools.getJaiTemplatesXML().getParameterBlockByName(currFunc);
        if (xmlPB != null) {
            jaiTemplates = xmlPB.getTemplate();
            for (JaiOperationDescriptor tlt : jaiTemplates) {
                if (tlt.getTemplatename().equalsIgnoreCase("default")) {
                    defaultisset = true;
                } else {
                    callstrings.add(tlt.getTemplatename());
                }
            }
        }
        java.util.Collections.sort(callstrings);
        callstrings.add(0, "default");
        if (defaultisset == false) {
            ParameterBlockJAI pb = new ParameterBlockJAI(currFunc.toLowerCase());
            IqmTools.getJaiTemplatesXML().setTemplate(currFunc, "default", pb);
        }

        callstrings.add("<New Template>");


        for (String s : callstrings) {
            templateList.addElement(s);
        }
        getChooseParameterBlock().validate();
    }

    public void setSelectedItem(int index){
        getChooseParameterBlock().setSelectedIndex(index);
    }

    private boolean shouldBTN_saveEnable() {
        return !userHasToChangeName && !userWantsToChangeName;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cbox_chooseParameterBlock = new javax.swing.JComboBox();
        lbl_tn              = new javax.swing.JLabel();
        jSeparator1         = new javax.swing.JSeparator();
        txt_newTemplateName = new javax.swing.JTextField();
        btn_delete          = new javax.swing.JButton();
        btn_changename      = new javax.swing.JButton();
        btn_close           = new javax.swing.JButton();
        btn_save            = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Template manager");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        cbox_chooseParameterBlock.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbox_chooseParameterBlockItemStateChanged(evt);
            }
        });

        lbl_tn.setText("Template name");

        txt_newTemplateName.setEditable(false);
        txt_newTemplateName.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txt_newTemplateNameKeyReleased(evt);
            }
        });

        btn_delete.setText("Delete selected template");
        btn_delete.setEnabled(false);
        btn_delete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_deleteActionPerformed(evt);
            }
        });

        btn_changename.setText("Change name");
        btn_changename.setEnabled(false);
        btn_changename.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_changeNameActionPerformed(evt);
            }
        });

        btn_close.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btn_close.setText("Close");
        btn_close.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_closeActionPerformed(evt);
            }
        });

        btn_save.setText("Save current settings to template");
        btn_save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_saveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cbox_chooseParameterBlock, 0, 395, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lbl_tn)
                        .addGap(84, 84, 84)
                        .addComponent(txt_newTemplateName, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btn_delete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btn_changename, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE))
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btn_save, javax.swing.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btn_close)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(cbox_chooseParameterBlock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(2, 2, 2)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_delete)
                    .addComponent(btn_changename))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_tn)
                    .addComponent(txt_newTemplateName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_close)
                    .addComponent(btn_save))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_changeNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_changenameActionPerformed
    String templatename = (String) getChooseParameterBlock().getSelectedItem();
        if (txt_newTemplateName.isEditable()) {
            txt_newTemplateName.setEditable(false); //set back
            userWantsToChangeName = false; //set back
            btn_delete.setEnabled(true);
            btn_save.setEnabled(true);
            btn_changename.setText("Change name");
            JaiOperationDescriptor template = IqmTools.getJaiTemplatesXML().getTemplateByName(IqmTools.getCurrImgProcessFunc(), templatename);
            if (template != null) {
            	String newTemplateName = txt_newTemplateName.getText();
                System.out.println("TemplateManagerGUI Change template name: " + templatename + " to: " + newTemplateName);
                //get data from current template
                ParameterBlockJAI pb = new ParameterBlockJAI(IqmTools.getCurrImgProcessFunc());
                pb = IqmTools.getJaiTemplatesXML().loadParameterBlockFromTemplate(pb, template);
                //Delete template
                deleteTemplate(templatename);
                //Save under new name
                IqmTools.getJaiTemplatesXML().setTemplate(IqmTools.getCurrImgProcessFunc(), newTemplateName, pb);
                //Rebuild
                fillChooseParameterBlock();
                //getChooseParameterBlock().setSelectedItem(templatename);
                getChooseParameterBlock().setSelectedItem(newTemplateName);            
                cbox_chooseParameterBlockItemStateChanged(null);           
                //txt_newTemplateName.setText(templatename); //default text for new name is old name
                this.lastTemplatename = newTemplateName;            
                txt_newTemplateName.setText((String) getChooseParameterBlock().getSelectedItem());         //default text for new name is nothing              
            }
        } else {
            userWantsToChangeName = true;
            txt_newTemplateName.setEditable(true);
            btn_delete.setEnabled(false);
            btn_save.setEnabled(false);
            btn_changename.setText("Save new name");
            txt_newTemplateName.setText(templatename);
        }
    }//GEN-LAST:event_btn_changenameActionPerformed

    /**
     * This method is called, when the user clicks on the delete button.
     * @param evt
     */
    private void btn_deleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_deleteActionPerformed
        String templatename = (String) getChooseParameterBlock().getSelectedItem();
        //getChooseParameterBlock().removeItemAt(getChooseParameterBlock().getSelectedIndex());
        deleteTemplate(templatename);
        fillChooseParameterBlock();
        getChooseParameterBlock().setSelectedItem("default");
        cbox_chooseParameterBlockItemStateChanged(null);
        //lastTemplatename = null;
        lastTemplatename = "default";
               
        //Not needed here: chooseParameterBlockChoosen("default");
    }//GEN-LAST:event_btn_deleteActionPerformed

    /**
     * This function sets the GUIs ParameterBlock to the user's choice.<br />
     * This function is called, when the changes the item in the combo-box.
     * @author Philipp W. <java@scaenicus.net>
     * @param evt Unused meta-data from the closing of the item changeing.
     */
    private void cbox_chooseParameterBlockItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbox_chooseParameterBlockItemStateChanged
        if (getChooseParameterBlock().getSelectedIndex() == getChooseParameterBlock().getItemCount() - 1) {
            btn_changename.setEnabled(false);
            btn_delete.setEnabled(false);
            btn_delete.setText("Delete selected template");
            txt_newTemplateName.setEditable(true);
            txt_newTemplateName.setText("Enter new template-name!");
            userHasToChangeName = true;
            btn_save.setEnabled(shouldBTN_saveEnable());
        } else if (getChooseParameterBlock().getSelectedIndex() == 0) {
            btn_changename.setEnabled(false);
            btn_delete.setEnabled(false);
            //btn_delete.setText("Reset to FACTORY defaults");
            btn_delete.setText("Delete selected template");
            txt_newTemplateName.setEditable(false);
            //txt_newTemplateName.setText("Default template can not be renamed!");
            txt_newTemplateName.setText("Default template can not be changed!");
            userHasToChangeName = false;
            btn_save.setEnabled(false);
        } else {
            btn_changename.setEnabled(true);
            btn_delete.setEnabled(true);
            btn_delete.setText("Delete selected template");
            txt_newTemplateName.setEditable(false);
            txt_newTemplateName.setText("");
            userHasToChangeName = false;
            btn_save.setEnabled(shouldBTN_saveEnable());
            //Not needed here: chooseParameterBlockChoosen(choosen);
        }
    }//GEN-LAST:event_cbox_chooseParameterBlockItemStateChanged

    private void txt_newTemplateNameKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_newTemplateNameKeyReleased
        userHasToChangeName = false;
        btn_save.setEnabled(shouldBTN_saveEnable());
    }//GEN-LAST:event_txt_newTemplateNameKeyReleased

    private void btn_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_saveActionPerformed
        String templatename;
        if (txt_newTemplateName.isEditable()) {
            templatename = txt_newTemplateName.getText();
        } else {
            templatename = (String) getChooseParameterBlock().getSelectedItem();
        }
        System.out.println("Create template: " + templatename);
        IqmTools.getJaiTemplatesXML().setTemplate(IqmTools.getCurrImgProcessFunc(), templatename, IqmTools.getCurrParameterBlockJAI());
        fillChooseParameterBlock();
        getChooseParameterBlock().setSelectedItem(templatename);
        cbox_chooseParameterBlockItemStateChanged(null);
        txt_newTemplateName.setText("");
        this.lastTemplatename = templatename;
    }//GEN-LAST:event_btn_saveActionPerformed

    private void btn_closeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_closeActionPerformed
        this.setVisible(false);
        callingGUI.fillChooseParameterBlock();
        callingGUI.setChoosenTemplate(this.lastTemplatename);
    }//GEN-LAST:event_btn_closeActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        btn_closeActionPerformed(null);
    }//GEN-LAST:event_formWindowClosing

    /**
     * Initializes and/or returns the combo-box used to choose existing templates (parameter block).
     * @author Philipp W. <java@scaenicus.net>
     * @return JComboBox Representation of the combo-box.
     */
    private javax.swing.JComboBox getChooseParameterBlock() {
        if (templateList == null) {
            templateList = new javax.swing.DefaultComboBoxModel();
            templateList.addElement("default");
            templateList.addElement("<New Template>");
            cbox_chooseParameterBlock.setModel(templateList);
            fillChooseParameterBlock();
            getChooseParameterBlock().setSelectedIndex(0);
            cbox_chooseParameterBlockItemStateChanged(null);
        }
        return cbox_chooseParameterBlock;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_changename;
    private javax.swing.JButton btn_close;
    private javax.swing.JButton btn_delete;
    private javax.swing.JButton btn_save;
    private javax.swing.JComboBox cbox_chooseParameterBlock;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lbl_tn;
    private javax.swing.JTextField txt_newTemplateName;
    // End of variables declaration//GEN-END:variables
}
//    /**
//     * This function is called, if the user presses a key on the combo-box.<br/>
//     * On [ENTER] or [RETURN] the current settings are stored to jaitemplates.xml with the same name, as the current selected name. Default can be overwritten by this. <br />
//     * On [DEL] the currently selected template is deleted from jaitemplates.xml.
//     * @author Philipp W. <java@scaenicus.net>
//     * @param evt Meta-data, including the pressed key.
//     */
//    private void chooseParameterBlockKeyPressed(java.awt.event.KeyEvent evt) {
//        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
//            txt_newTemplateName.setText((String) getChooseParameterBlock().getSelectedItem());
//        } else if (evt.getKeyCode() == KeyEvent.VK_DELETE && getChooseParameterBlock().getSelectedIndex() > 0 && getChooseParameterBlock().getSelectedIndex() < getChooseParameterBlock().getItemCount() - 1) {
//            String templatename = (String) getChooseParameterBlock().getSelectedItem();
//            //getChooseParameterBlock().removeItemAt(getChooseParameterBlock().getSelectedIndex());
//            deleteTemplate(templatename);
//            fillChooseParameterBlock();
//            getChooseParameterBlock().setSelectedItem("default");
//            chooseParameterBlockChoosen("default");
//            this.setParameterValues();
//        }
//    }
//    /**
//     * This function is called, if the user presses a key on the text-box.<br/>
//     * On [ENTER] or [RETURN] the current settings are stored to jaitemplates.xml with the same name, as the String in the text-box. Any template can be overwritten by this. <br />
//     * @author Philipp W. <java@scaenicus.net>
//     * @param evt Meta-data, including the pressed key.
//     */
//    private void newTemplateNameKeyPressed(java.awt.event.KeyEvent evt) {
//        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
//            String templatename = txt_newTemplateName.getText();
//            System.out.println("Create/overwrite template: " + templatename);
//            IqmTools.getJaiTemplatesXML().setTemplate(IqmTools.getCurrImgProcessFunc(), templatename, IqmTools.getCurrParameterBlockJAI());
////            int index = chooseParameterBlock.getSelectedIndex();
////            int count = chooseParameterBlock.getItemCount();
////            chooseParameterBlock.removeItemAt(count - 1);
////            if (index > 0 && index < count && !templatename.equals(chooseParameterBlock.getSelectedItem())) {
////                //chooseParameterBlock.removeItemAt(index);
////                chooseParameterBlock.addItem(templatename);
////            }
////            chooseParameterBlock.addItem("<New Template>");
////            chooseParameterBlock.setSelectedItem(templatename);
//            fillChooseParameterBlock();
//            getChooseParameterBlock().setSelectedItem(templatename);
//            txt_newTemplateName.setText("");
//        }
//    }
//    /**
//     * Initializes and/or returns the text-field used to set new, and update existing templates.
//     * @return Representations of the text-field.
//     * @author Philipp W. <java@scaenicus.net>
//     */
//    private JTextField txt_newTemplateName {
//
//        if (newTemplateName == null) {
//            newTemplateName = new javax.swing.JTextField();
//            newTemplateName.setText("");
//            newTemplateName.addKeyListener(new java.awt.event.KeyAdapter() {
//
//                @Override
//                public void keyPressed(java.awt.event.KeyEvent evt) {
//                    newTemplateNameKeyPressed(evt);
//                }
//            });
//        }
//        return newTemplateName;
//    }


